<template>
  <view class="container">
    <view class="card-form">
      <view class="form-row">
        <view class="form-group">
          <label>会员卡号：<span style="color: red;">*</span></label>
          <view class="inline-input">
            <input type="number" v-model="cardNumber" placeholder="输入会员卡号(F2)" class="input-field" required/>
            <button @click="generateCardNumber" class="generate-button" size="mini">生成</button>
          </view>
        </view>
        <view class="form-group">
          <label>会员姓名：<span style="color: red;">*</span></label>
          <input type="text" v-model="name" placeholder="输入会员姓名" class="input-field" required/>
        </view>
      </view>

      <view class="form-row">
        <view class="form-group">
          <label>手机号：<span style="color: red;">*</span></label>
          <input type="number" v-model="phone" placeholder="输入会员手机号" class="input-field" required/>
        </view>
        <view class="form-group">
          <label>生日：</label>
          <picker mode="date" :value="date" :start="startDate" :end="endDate" @change="bindDateChange">
            <view class="input-field">{{date}}</view>
          </picker>
        </view>
      </view>

      <view class="form-row">
        <view class="form-group">
          <label>性别：</label>
          <radio-group @change="radioChange" class="gender-options">
            <label class="uni-list-cell uni-list-cell-pd" v-for="(item, index) in items" :key="item.value">
              <radio :value="item.value" :checked="index === current" />{{ item.name }}
            </label>
          </radio-group>
        </view>
        <view class="form-group">
          <label>会员等级：</label>
          <select v-model="level" class="input-field">
            <option value="" disabled>请选择会员等级</option>
            <option v-for="level in levels" :key="level.id" :value="level.id">{{ level.name }}</option>
          </select>
        </view>
      </view>

     <!-- <view class="form-row">
        <view class="form-group">
          <label>售卡工本费：</label>
          <input type="number" v-model="cardCost" class="input-field" />
        </view>
        <view class="form-group">
          <label>支付方式：</label>
          <select v-model="paymentMethod" class="input-field">
            <option value="default">请选择支付方式</option>
          </select>
        </view>
      </view> -->

      <!-- <view class="form-row">
        <view class="form-group">
          <label>账户金额：</label>
          <input type="number" v-model="accountBalance" class="input-field" />
        </view>
        <view class="form-group">
          <label>账户积分：</label>
          <input type="number" v-model="accountPoints" class="input-field" />
        </view>
      </view>

      <view class="form-row">
        <view class="form-group full-width">
          <label>推荐人：</label>
          <view class="inline-input">
            <input type="text" v-model="referrer" placeholder="点击搜索推荐人" class="input-field" />
            <button @click="searchReferrer" class="search-button" size="mini">点击搜索</button>
          </view>
        </view>
        <view class="form-group">
          <label>提成员工：</label>
          <select v-model="employee" class="input-field">
            <option value="default">请选择提成员工</option>
          </select>
        </view>
      </view> -->

      <view class="form-row">
        <view class="form-group photo-upload">
          <label>上传照片：</label>
          <view class="photo-container">
            <image :src="photoUrl" alt="会员照片" v-if="photoUrl" />
            <view v-else class="placeholder">客户照片</view>
          </view>
		  <view class="" style="display: flex;">
          <button @click="chooseImage" class="upload-button" size="mini">上传</button>
          <button @click="deletePhoto" v-if="photoUrl" class="delete-button" size="mini">删除</button>
		  </view>
        </view>
      </view>
      <button type="default" @click="insertCard">添加</button>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      cardNumber: '', // 会员卡号
      name: '',
      phone: '',
      date: '1960-01-01', // 默认日期
      startDate: '1950-01-01', // 开始日期
      endDate: '2028-12-31', // 结束日期
      current: 0, // 默认选中的性别
      items: [
        { name: "保密", value: "保密" },
        { name: "男", value: "男" },
        { name: "女", value: "女" }
      ],
      levels: [], // 会员等级列表
      level: '', // 选中的会员等级
      cardCost: 0,
      paymentMethod: 'default',
      accountBalance: 0,
      accountPoints: 0,
      referrer: '',
      employee: '',
      photoUrl: '', // 图片URL
      photoPath: '', // 图片路径
      userInfo: {}
    };
  },
  methods: {
    radioChange(e) {
      this.current = this.items.findIndex(item => item.value === e.detail.value);
    },
    searchReferrer() {
      // 实现推荐人搜索逻辑
    },
	 validateForm() {
      if (!this.cardNumber || !this.name) {
        uni.showToast({
          title: '请填写所有必填字段',
          icon: 'none',
          duration: 2000,
        });
        return;
      }
      // 调用提交函数
      this.insertCard();
    },
    chooseImage() {
      uni.chooseImage({
        count: 1, // 默认9
        sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
        success: (chooseImageRes) => {
          const tempFilePaths = chooseImageRes.tempFilePaths;

          // 预览图片 urls: res.tempFilePaths,
          uni.previewImage({
            current: tempFilePaths[0], // 当前显示图片的http链接或者本地路径
            urls: tempFilePaths // 需要预览的图片http链接列表
          });

          const uploadTask = uni.uploadFile({
            url: 'https://erp.kzjpht.com/index/uploader/upload', // 开发者服务器地址
            filePath: tempFilePaths[0], // 要上传文件资源的路径
            name: 'file', // 文件对应的key,开发者在服务器端通过这个key可以获取到文件二进制内容
            formData: { // HTTP 请求中其他额外的 form data
              'user': 'test'
            },
            success: (uploadFileRes) => {
              const response = JSON.parse(uploadFileRes.data);
              if (response && response.path) {
                this.photoUrl = "https://erp.kzjpht.com/" + response.path;
                this.photoPath = response.path; // 保存图片路径

              } else {
                console.error('图片上传失败');
              }
            },
            fail: (error) => {
              console.error('uploadFile fail:', error);
              // 处理上传失败的错误
            }
          });

          uploadTask.onProgressUpdate((res) => {
            console.log('上传进度' + res.progress + '%');
          });
        },
        fail: (error) => {
          console.error('chooseImage fail:', error);
          // 处理选择图片失败的错误
        }
      });
    },
    //检查是否登录
    checkLoginStatus() {
      const token = uni.getStorageSync('token');
      if (token) {
        this.userInfo = JSON.parse(uni.getStorageSync('userInfo'));
      } else {
        this.userInfo = {};
        this.$router.push('/pages/login/login');
      }
    },
    async deletePhoto() {
      const res = await this.$myRuquest({
        url: '/index/uploader/img_del',
        data: {
          "img_path": this.photoPath,
        },
      })
      if (res.data.code == 1) {
        this.photoUrl = "";
        this.photoPath = "";
        uni.showToast({
          title: '删除成功',
          duration: 2000,
          icon: 'none'
        })
      }
    },
    async getLevels() {
      // 获取会员等级列表
      const res = await this.$myRuquest({
        url: '/index/plugin.users/getLevels',
        method: 'POST',
		data: {
		  user_id: this.userInfo.user_id
		}
      });
      if (res.data.code === 200) {
        this.levels = res.data.data;
      } else {
        uni.showToast({
          title: res.data.message,
          duration: 2000,
          icon: 'none'
        });
      }
    },
    bindDateChange(e) {
      this.date = e.detail.value;
    },
    generateCardNumber() {
      // 生成随机10位数字卡号
      this.cardNumber = Math.random().toString().slice(2, 12);
    },
    async insertCard() {
		
		if(this.cardNumber.length <= 8 || this.name.length <= 1 || this.phone.length <= 10){
			
			uni.showToast({
			  title: "请检查格式,必填写不能为空",
			  duration: 2000,
			  icon: 'none'
			});
			
			return false;
		}
      const res = await this.$myRuquest({
        url: '/index/plugin.foreground/insert_foreg_user',
        method: 'POST',
        data: {
          card_number: this.cardNumber,
          name: this.name,
          phone: this.phone,
          birth_date: this.date,
          gender: this.items[this.current].value,
          level: this.level,
          card_cost: this.cardCost,
          payment_method: this.paymentMethod,
          account_balance: this.accountBalance,
          account_points: this.accountPoints,
          referrer: this.referrer,
          employee: this.employee,
          photo_url: this.photoPath,
          shop_id: this.userInfo.shop_id
        },
      });

      // 根据接口返回的结果进行相应处理
      if (res.data.code == 200) {
        alert('会员添加成功');
        // 重置表单
        this.resetForm();
      } else {
        alert('会员添加失败');
      }
    },
    resetForm() {
      this.cardNumber = '';
      this.name = '';
      this.phone = '';
      this.date = '2023-01-01';
      this.current = 0;
      this.level = '';
      this.cardCost = 0;
      this.paymentMethod = 'default';
      this.accountBalance = 0;
      this.accountPoints = 0;
      this.referrer = '';
      this.employee = '';
      this.photoUrl = '';
      this.photoPath = '';
    }
  },
  created() {
    this.checkLoginStatus();
	console.log(this.userInfo);
    this.getLevels(); // 获取会员等级列表
  },
};
</script>

<style>
.container {
  padding: 20px;
}

.input-field {
  width: 80%;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  outline: none;
}

.card-form {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.form-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
}

.form-group {
  flex: 1;
  display: flex;
  flex-direction: column;
  margin-right: 10px;
}

.form-group:last-child {
  margin-right: 0;
}

label {
  margin-bottom: 5px;
  color: #666;
}

input[type="text"],
input[type="number"],
input[type="date"],
select {
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.gender-options {
  display: flex;
  align-items: center;
}

.gender-options label {
  margin-right: 10px;
  display: flex;
  align-items: center;
}

.radio {
  margin-right: 5px;
}

button {
  background-color: #4cd964;
  color: #fff;
  border: none;
  padding: 8px 12px;
  border-radius: 4px;
  cursor: pointer;
}

button:hover {
  background-color: #45c853;
}

.full-width {
  flex: 2;
}

.inline-input {
  display: flex;
  align-items: center;
}

.inline-input input {
  flex: 1;
}

.inline-input .search-button,
.inline-input .generate-button {
  margin-left: 10px;
  padding: 8px 16px;
}

.photo-upload {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.photo-container {
  width: 300px;
  height: 300px;
  border: 1px dashed #ddd;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 10px;
}

.photo-container image {
  max-width: 100%;
  max-height: 100%;
}

.placeholder {
  color: #bbb;
}

.delete-button {
  background-color: #e74c3c;
  color: #fff;
  margin-top: 10px;
  margin-left: 5px;
}

.upload-button {
  background-color: #4cd964;
  color: #fff;
  margin-top: 10px;
  
}
</style>
